package com.game.modular.game.playerMatch.service;

import cn.hutool.core.date.DateUtil;
import com.game.comment.exection.ServiceException;
import com.game.modular.game.battle.info.base.PvpPlayerInfo;
import com.game.modular.game.battle.info.base.PvpPlayerInfoServiceImpl;
import com.game.modular.game.playerMatch.domain.PvpCity;
import com.game.modular.game.playerMatch.domain.PvpCityBuildings;
import com.game.modular.game.playerAssets.service.PlayerBagServiceImpl;
import com.game.modular.game.playerMatch.service.base.PvpCityBuildBaseServiceImpl;
import com.game.modular.gameCore.cultivate.domain.CoreProp;
import com.game.modular.gameCore.cultivate.service.impl.CorePropServiceImpl;
import com.game.modular.gameCore.map.domain.CoreCityBuildings;
import com.game.modular.gameCore.map.service.impl.CoreCityBuildingsServiceImpl;
import com.game.modular.gameCore.map.service.impl.CoreCityServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * 城池信息(PvpCity)表服务实现类
 *
 * @author cxy
 * @since 2024-07-22 15:13:38
 */
@Slf4j
@Service
public class PvpCityBuildServiceImpl extends PvpCityBuildBaseServiceImpl {
    @Resource
    private CoreCityServiceImpl coreCityServiceImpl;
    @Resource
    private PvpCityServiceImpl pvpCityService;
    @Resource
    private CoreCityBuildingsServiceImpl coreCityBuildingsServiceImpl;
    @Resource
    private PlayerBagServiceImpl playerBagService;
    @Resource
    private PlayerMatchServiceImpl playerMatchServiceImpl;
    @Resource
    private CorePropServiceImpl corePropServiceImpl;
    @Resource
    private PvpPlayerInfoServiceImpl pvpPlayerInfoServiceImpl;

    /**
     * 获取玩家当前对局所有城池建筑
     */
    public Map<Long, Map<String, PvpCityBuildings>> map(Long playerId) {
        Long currentMatchId = playerMatchServiceImpl.currentMatchId(playerId);
        List<PvpCityBuildings> pvpCityBuildings =
                eqList(PvpCityBuildings.builder().playerId(playerId).matchId(currentMatchId).build());
        Map<Long, Map<String, PvpCityBuildings>> map = new HashMap<>();
        pvpCityBuildings.forEach(item -> {
            Map<String, PvpCityBuildings> map1 = map.computeIfAbsent(item.getCoreCityId(), k -> new HashMap<>());
            map1.put(item.getNo().toString(), item);
            map.put(item.getCoreCityId(), map1);
        });
        return map;
    }

    public PvpCityBuildings build(
            Long playerId,
            Long targetCityId,
            Integer cityBuildNo,
            Long coreCityBuildingId,
            Long coreCityId
    ) {
        // 获取账户
        Long currentMatchId = playerMatchServiceImpl.currentMatchId(playerId);

        PvpPlayerInfo pvpPlayerInfo = pvpPlayerInfoServiceImpl.get(currentMatchId, playerId);
        Set<Long> currentCity = pvpPlayerInfo.getCurrentCity();
        if (!currentCity.contains(targetCityId)) {
            throw new ServiceException("当前城池不属于你");
        }if (pvpPlayerInfo.getIsExit() == 1) {
            throw new ServiceException("你已退出对局");
        }

        CoreCityBuildings coreCityBuilding = coreCityBuildingsServiceImpl.getCache(coreCityBuildingId);
        if (coreCityBuilding.getLevel() > 1) {
            throw new ServiceException("请先建筑1级建筑");
        }

        Long levelUpTime = coreCityBuilding.getLevelUpTime();
        Long levelUpCost = coreCityBuilding.getLevelUpCost();

        Integer landNum = coreCityServiceImpl.getCache(targetCityId).getLandNum();
        int size = eqList(PvpCityBuildings.builder().matchId(currentMatchId).coreCityId(coreCityId).build()).size();
        if (size >= landNum) {
            throw new ServiceException("城池内建筑数量已达上限");
        }
        playerBagService.use(playerId, 4L, levelUpCost);

        PvpCityBuildings pvpCityBuildings = new PvpCityBuildings();
        pvpCityBuildings.init(playerId, targetCityId, cityBuildNo, currentMatchId);
        pvpCityBuildings.building(coreCityBuildingId, levelUpTime, coreCityBuilding);
        saveCache(pvpCityBuildings);
        return pvpCityBuildings;
    }

    public PvpCityBuildings buildUp(Long playerId, Long targetCityId, Integer no) {
        // 获取账户
        PvpCityBuildings pvpCityBuildings = allEqSelect(PvpCityBuildings.builder()
                .matchId(playerMatchServiceImpl.currentMatchId(playerId))
                .coreCityId(targetCityId)
                .no(no)
                .build());
        if (pvpCityBuildings == null || pvpCityBuildings.getStatus() != 1) {
            throw new ServiceException("当前建造不可操作");
        }


        Long coreCityBuildingId = pvpCityBuildings.getCorePvpCityBuildingId();
        CoreCityBuildings up = coreCityBuildingsServiceImpl.getCache(coreCityBuildingId + 1);
        boolean equals = pvpCityBuildings.getType().equals(up.getType());
        if (!equals) {
            throw new ServiceException("升级条件不满足");
        }

        Long levelUpCost = up.getLevelUpCost();// 铜币
        playerBagService.use(playerId, levelUpCost, 4L);

        Long levelUpTime = up.getLevelUpTime();// 秒
        Long upId = up.getId();
        Integer upLevel = up.getLevel();
        pvpCityBuildings.setCorePvpCityBuildingId(upId);
        pvpCityBuildings.setPlayerId(playerId);
        pvpCityBuildings.setStatus(2);
        pvpCityBuildings.setLevel(upLevel);
        pvpCityBuildings.setFinishTime(DateUtil.offsetSecond(new Date(), levelUpTime.intValue()).getTime());
        saveCache(pvpCityBuildings);
        return pvpCityBuildings;
    }

    public void remove(Long playerId, Long targetCityId, Integer no) {
        // 获取账户
        Long currentMatchId = playerMatchServiceImpl.currentMatchId(playerId);
        PvpCityBuildings pvpCityBuildings = allEqSelect(PvpCityBuildings.builder()
                .matchId(currentMatchId)
                .coreCityId(targetCityId)
                .build());
        if (pvpCityBuildings == null) {
            throw new ServiceException("建筑不存在");
        }
        if (pvpCityBuildings.getStatus() != 1) {
            throw new ServiceException("当前建造不可操作");
        }
        removeCache(currentMatchId, targetCityId, no);
        /////////////////// 减少城市内政以及产力值
        CoreCityBuildings cache = coreCityBuildingsServiceImpl.getCache(pvpCityBuildings.getCorePvpCityBuildingId());
        PvpCity pvpCity = pvpCityService.getPlayerCity(playerId, targetCityId, currentMatchId);
        pvpCity.setGrainRate(pvpCity.getGrainRate() - cache.getGrainRate());
        pvpCity.setCopperRate(pvpCity.getCopperRate() - cache.getCopperRate());
        pvpCity.setReadyArmyRate(pvpCity.getReadyArmyRate() - cache.getReadyArmyRate());
        pvpCityService.update(pvpCity);
    }

    /**
     * 使用 内政建筑道具
     */
    public PvpCityBuildings useCityBuildingProp(Long playerId, Long targetCityId, Integer no, Long corePropId) {
        PvpCityBuildings pvpCityBuildings = allEqSelect(PvpCityBuildings.builder()
                .matchId(playerMatchServiceImpl.currentMatchId(playerId))
                .coreCityId(targetCityId)
                .no(no)
                .build());
        if (pvpCityBuildings == null || pvpCityBuildings.getStatus() == 1) {
            throw new ServiceException("当前建造无法使用当前物品");
        }

        // 获取加速券
        // 2005	能人巧匠	2	使用可以使当前正在升级的建筑，立刻完成升级
        CoreProp cache = corePropServiceImpl.getCache(corePropId);

        // 保存
        // saveCache(pvpCityBuildings);

        throw new ServiceException("功能未开放");

        // return pvpCityBuildings;
    }

    /**
     * 城池内政建造任务
     *
     * @param matchId 对局id
     */
    public void tryCityBuildingTask(Long matchId) {
        listCache(matchId).forEach(item -> {
            Integer status = item.getStatus();
            //  建造任务
            if (status==2){
                Long finishTime = item.getFinishTime();
                long thisTime = new Date().getTime();
                if (thisTime >= finishTime) {
                    item.setStatus(1);


                    // // 增加城池的生产力
                    // CoreCityBuildings cache = coreCityBuildingsServiceImpl.getCache(item.getCorePvpCityBuildingId());
                    // PvpCity pvpCity = pvpCityService.getPlayerCity(item.getPlayerId(), item.getCoreCityId(), item.getMatchId());
                    // pvpCity.setGrainRate(pvpCity.getGrainRate() + cache.getGrainRate());
                    // pvpCity.setCopperRate(pvpCity.getCopperRate() + cache.getCopperRate());
                    // pvpCity.setReadyArmyRate(pvpCity.getReadyArmyRate() + cache.getReadyArmyRate());
                    // pvpCityService.update(pvpCity);
                }
            }

            // 保存
            saveCache(item);
        });
    }
}